﻿using System;
using System.IO;
using USU.MetricsMonitor.Common;

namespace USU.MetricsMonitor.LogProvider
{
	public class SvnLogProvider : BaseLogProvider
	{
		public static readonly string SvnExeArgumentsPattern = @"log ""{0}"" -r {1}:HEAD -v --xml";
        public static readonly string SvnExeARgumentsPatternWithLimit = SvnExeArgumentsPattern + " -l {2}";

        public static readonly string TempLogFile = "temp.log";

        public SvnLogProvider(string repositaryPath, string logLocalDirectory)
            : base(repositaryPath, logLocalDirectory) { }

        private Stream GetStream(string arguments)
        {
            string path = Path.Combine(LogLocalDirectory, TempLogFile);
            try
            {
                using (var file = File.Open(path, FileMode.Create, FileAccess.Write))
                using (var consoleApp = new ConsoleApplication(Utils.SvnExeFileName, arguments))
                {
                    consoleApp.RedirectOutputTo(file);
                    consoleApp.WaitForExit();
                }
            }
            catch (ConsoleApplicationException e)
            {
                throw new LogProviderException("Ошибка при получении log'а", e);
            }
            return File.Open(path, FileMode.Open, FileAccess.Read);
        }

        public override Stream GetLog(Revision startRevision)
        {
            return GetStream(
                String.Format(SvnExeArgumentsPattern, RepositaryPath, startRevision)
            );
        }

        public override Stream GetLog(Revision startRevision, uint maxnumberOfLogEntries)
        {
            return GetStream(
                String.Format(SvnExeARgumentsPatternWithLimit, RepositaryPath, startRevision, maxnumberOfLogEntries)
            );
         }
    }
}
